// 游戏增强系统 - 添加更多有趣的游戏元素
(function() {
    'use strict';
    
    // 环境互动系统 - 可破坏物品和爆炸桶
    class EnvironmentSystem {
        constructor(gameEngine) {
            this.gameEngine = gameEngine;
            this.destructibles = [];
            this.explosives = [];
            this.initialized = false;
        }
        
        initialize() {
            if (this.initialized) return;
            
            this.createEnvironmentObjects();
            this.initialized = true;
            console.log('🌍 环境互动系统已激活');
        }
        
        createEnvironmentObjects() {
            // 清除现有对象
            this.destructibles = [];
            this.explosives = [];
            
            // 创建可破坏的桌子/椅子
            for (let i = 0; i < 8; i++) {
                this.destructibles.push({
                    x: Math.random() * 800 + 100,
                    y: Math.random() * 600 + 100,
                    width: 40,
                    height: 30,
                    health: 3,
                    maxHealth: 3,
                    type: 'furniture',
                    destroyed: false,
                    debris: false
                });
            }
            
            // 创建爆炸桶
            for (let i = 0; i < 3; i++) {
                this.explosives.push({
                    x: Math.random() * 700 + 150,
                    y: Math.random() * 500 + 150,
                    width: 25,
                    height: 35,
                    health: 1,
                    type: 'explosive_barrel',
                    exploded: false,
                    radius: 80
                });
            }
        }
        
        update(deltaTime) {
            if (!this.initialized) return;
            
            this.checkBulletCollisions();
            this.checkPlayerCollisions();
        }
        
        checkBulletCollisions() {
            this.gameEngine.bullets.forEach((bullet, bulletIndex) => {
                // 检查子弹与可破坏物的碰撞
                this.destructibles.forEach(obj => {
                    if (!obj.destroyed && this.isColliding(bullet, obj)) {
                        obj.health--;
                        this.gameEngine.bullets.splice(bulletIndex, 1);
                        
                        if (obj.health <= 0) {
                            obj.destroyed = true;
                            this.createDebris(obj.x, obj.y);
                            window.gameEnhancements?.visualEffects?.createImpact(obj.x, obj.y, '#8B4513');
                        }
                    }
                });
                
                // 检查子弹与爆炸桶的碰撞
                this.explosives.forEach(explosive => {
                    if (!explosive.exploded && this.isColliding(bullet, explosive)) {
                        this.gameEngine.bullets.splice(bulletIndex, 1);
                        this.explodeBarrel(explosive);
                    }
                });
            });
        }
        
        checkPlayerCollisions() {
            if (!window.player) return;
            
            // 检查玩家与爆炸的碰撞
            this.explosives.forEach(explosive => {
                if (explosive.exploding && this.getDistance(window.player, explosive) < explosive.radius) {
                    const damage = Math.max(1, Math.floor(30 * (1 - this.getDistance(window.player, explosive) / explosive.radius)));
                    this.damagePlayer(damage);
                    explosive.exploding = false; // 防止重复伤害
                }
            });
        }
        
        explodeBarrel(explosive) {
            explosive.exploded = true;
            explosive.exploding = true;
            
            // 创建爆炸效果
            window.gameEnhancements?.visualEffects?.createExplosion(explosive.x, explosive.y, explosive.radius);
            
            // 对范围内的僵尸造成伤害
            this.gameEngine.zombies.forEach(zombie => {
                const distance = this.getDistance(zombie, explosive);
                if (distance < explosive.radius) {
                    const damage = Math.floor(50 * (1 - distance / explosive.radius));
                    zombie.health -= damage;
                    window.gameEnhancements?.visualEffects?.createDamageText(zombie.x, zombie.y, damage, '#FF4500');
                    
                    if (zombie.health <= 0) {
                        window.gameEnhancements?.comboSystem?.addKill();
                    }
                }
            });
            
            console.log('💥 爆炸桶被引爆！');
        }
        
        createDebris(x, y) {
            for (let i = 0; i < 5; i++) {
                this.gameEngine.particles.push({
                    x: x + Math.random() * 40,
                    y: y + Math.random() * 30,
                    vx: (Math.random() - 0.5) * 200,
                    vy: (Math.random() - 0.5) * 200,
                    life: 2,
                    maxLife: 2,
                    color: '#8B4513',
                    size: Math.random() * 4 + 2
                });
            }
        }
        
        render(ctx) {
            if (!this.initialized) return;
            
            // 渲染可破坏物品
            this.destructibles.forEach(obj => {
                if (!obj.destroyed) {
                    ctx.fillStyle = '#8B4513';
                    ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
                    
                    // 损坏效果
                    if (obj.health < obj.maxHealth) {
                        ctx.fillStyle = '#654321';
                        ctx.fillRect(obj.x + 2, obj.y + 2, obj.width - 4, obj.height - 4);
                    }
                }
            });
            
            // 渲染爆炸桶
            this.explosives.forEach(explosive => {
                if (!explosive.exploded) {
                    ctx.fillStyle = '#DC143C';
                    ctx.fillRect(explosive.x, explosive.y, explosive.width, explosive.height);
                    ctx.fillStyle = '#FF6347';
                    ctx.fillRect(explosive.x + 3, explosive.y + 3, explosive.width - 6, explosive.height - 6);
                }
            });
        }
        
        isColliding(obj1, obj2) {
            return obj1.x < obj2.x + obj2.width &&
                   obj1.x + (obj1.width || obj1.radius * 2) > obj2.x &&
                   obj1.y < obj2.y + obj2.height &&
                   obj1.y + (obj1.height || obj1.radius * 2) > obj2.y;
        }
        
        getDistance(obj1, obj2) {
            const dx = obj1.x - obj2.x;
            const dy = obj1.y - obj2.y;
            return Math.sqrt(dx * dx + dy * dy);
        }
        
        damagePlayer(damage) {
            if (window.player) {
                window.player.health -= damage;
                // window.gameEnhancements?.visualEffects?.screenShake(10); // 禁用震动
                if (window.player.updateHealthUI) window.player.updateHealthUI();
            }
        }
    }
    
    // 闪避系统 - 翻滚/冲刺机制
    class DodgeSystem {
        constructor() {
            this.isDodging = false;
            this.dodgeStartTime = 0;
            this.dodgeDuration = 300; // 300ms
            this.dodgeCooldown = 1000; // 1秒冷却
            this.lastDodgeTime = 0;
            this.dodgeDistance = 80;
            this.dodgeDirection = { x: 0, y: 0 };
            this.originalSpeed = 0;
        }
        
        initialize() {
            this.setupControls();
            console.log('🏃 闪避系统已激活 - 按空格键闪避');
        }
        
        setupControls() {
            document.addEventListener('keydown', (e) => {
                if (e.code === 'Space' && !this.isDodging) {
                    e.preventDefault();
                    this.attemptDodge();
                }
            });
        }
        
        attemptDodge() {
            const now = Date.now();
            if (now - this.lastDodgeTime < this.dodgeCooldown) return;
            if (!window.player || !window.gameEngine) return;
            if (window.gameEngine.gameState !== 'playing') return;
            
            // 确定闪避方向（基于当前移动方向）
            const keys = window.gameEngine.keys;
            let dx = 0, dy = 0;
            
            if (keys['KeyW'] || keys['ArrowUp']) dy = -1;
            if (keys['KeyS'] || keys['ArrowDown']) dy = 1;
            if (keys['KeyA'] || keys['ArrowLeft']) dx = -1;
            if (keys['KeyD'] || keys['ArrowRight']) dx = 1;
            
            // 如果没有方向输入，向鼠标方向闪避\n            if (dx === 0 && dy === 0) {\n                const mouseX = window.gameEngine.mouse.x;\n                const mouseY = window.gameEngine.mouse.y;\n                const angle = Math.atan2(mouseY - window.player.y, mouseX - window.player.x);\n                dx = Math.cos(angle);\n                dy = Math.sin(angle);\n            }
            
            // 归一化方向
            const length = Math.sqrt(dx * dx + dy * dy);
            if (length > 0) {
                dx /= length;
                dy /= length;
            }
            
            this.startDodge(dx, dy);
        }
        
        startDodge(dx, dy) {
            this.isDodging = true;
            this.dodgeStartTime = Date.now();
            this.lastDodgeTime = this.dodgeStartTime;
            this.dodgeDirection = { x: dx, y: dy };
            this.originalSpeed = window.player.speed;
            
            // 短暂无敌状态
            window.player.invulnerable = true;
            
            // 视觉效果
            window.gameEnhancements?.visualEffects?.createDodgeTrail(window.player.x, window.player.y);
            
            console.log('🏃 闪避执行');
        }
        
        update(deltaTime) {
            if (!this.isDodging || !window.player) return;
            
            const elapsed = Date.now() - this.dodgeStartTime;
            const progress = Math.min(elapsed / this.dodgeDuration, 1);
            
            if (progress >= 1) {
                this.endDodge();
                return;
            }
            
            // 缓动函数（快速开始，慢速结束）
            const easeOut = 1 - Math.pow(1 - progress, 3);
            
            // 应用闪避移动
            const speed = this.dodgeDistance * (deltaTime / 1000) * (1 - easeOut) * 8;
            window.player.x += this.dodgeDirection.x * speed;
            window.player.y += this.dodgeDirection.y * speed;
            
            // 边界检查
            window.player.x = Math.max(window.player.radius, Math.min(1000 - window.player.radius, window.player.x));
            window.player.y = Math.max(window.player.radius, Math.min(750 - window.player.radius, window.player.y));
        }
        
        endDodge() {
            this.isDodging = false;
            if (window.player) {
                window.player.invulnerable = false;
                window.player.speed = this.originalSpeed;
            }
        }
        
        isInvulnerable() {
            return this.isDodging && window.player?.invulnerable;
        }
    }
    
    // 连击系统 - 连续击杀奖励
    class ComboSystem {
        constructor() {
            this.combo = 0;
            this.lastKillTime = 0;
            this.comboTimeout = 3000; // 3秒内需要击杀以维持连击
            this.bestCombo = parseInt(localStorage.getItem('bestCombo') || '0');
            this.comboMultiplier = 1;
        }
        
        initialize() {
            console.log('🔥 连击系统已激活');
        }
        
        addKill() {
            const now = Date.now();
            
            if (now - this.lastKillTime > this.comboTimeout) {
                this.combo = 1;
            } else {
                this.combo++;
            }
            
            this.lastKillTime = now;
            this.updateMultiplier();
            this.checkComboRewards();
            this.showComboEffect();
            
            // 更新最佳连击记录
            if (this.combo > this.bestCombo) {
                this.bestCombo = this.combo;
                localStorage.setItem('bestCombo', this.bestCombo.toString());
                window.gameEnhancements?.visualEffects?.createComboText(window.player?.x || 500, window.player?.y || 400, `新记录! ${this.combo}x`, '#FFD700');
            }
        }
        
        updateMultiplier() {
            this.comboMultiplier = 1 + Math.min(this.combo * 0.1, 2); // 最大3倍奖励
        }
        
        checkComboRewards() {
            // 每5连击给予奖励
            if (this.combo % 5 === 0 && this.combo > 0) {
                this.giveComboReward();
            }
            
            // 特殊连击奖励
            if (this.combo === 10) {
                this.giveBonusReward('速度提升', () => {
                    if (window.player) window.player.speed *= 1.2;
                });
            } else if (this.combo === 20) {
                this.giveBonusReward('伤害提升', () => {
                    if (window.player?.currentWeapon) window.player.currentWeapon.damage *= 1.3;
                });
            } else if (this.combo === 30) {
                this.giveBonusReward('无敌时间', () => {
                    if (window.player) {
                        window.player.invulnerable = true;
                        setTimeout(() => {
                            if (window.player) window.player.invulnerable = false;
                        }, 5000);
                    }
                });
            }
        }
        
        giveComboReward() {
            const rewards = [
                () => this.healPlayer(10),
                () => this.giveAmmo(15),
                () => this.tempSpeedBoost()
            ];
            
            const reward = rewards[Math.floor(Math.random() * rewards.length)];
            reward();
        }
        
        giveBonusReward(name, effect) {
            effect();
            window.gameEnhancements?.visualEffects?.createComboText(
                window.player?.x || 500, 
                window.player?.y || 400, 
                `${name}!`, 
                '#00FF00'
            );
            console.log(`🏆 连击奖励: ${name} (${this.combo}x连击)`);
        }
        
        showComboEffect() {
            if (!window.player) return;
            
            let color = '#FFFFFF';
            if (this.combo >= 30) color = '#FFD700';
            else if (this.combo >= 20) color = '#FF4500';
            else if (this.combo >= 10) color = '#00FF00';
            else if (this.combo >= 5) color = '#00BFFF';
            
            window.gameEnhancements?.visualEffects?.createComboText(
                window.player.x, 
                window.player.y - 30, 
                `${this.combo}x`, 
                color
            );
        }
        
        update(deltaTime) {
            const now = Date.now();
            if (this.combo > 0 && now - this.lastKillTime > this.comboTimeout) {
                this.resetCombo();
            }
        }
        
        resetCombo() {
            if (this.combo > 0) {
                console.log(`💥 连击中断: ${this.combo}x`);
                this.combo = 0;
                this.comboMultiplier = 1;
            }
        }
        
        healPlayer(amount) {
            if (window.player && window.player.health < window.player.maxHealth) {
                window.player.health = Math.min(window.player.maxHealth, window.player.health + amount);
                if (window.player.updateHealthUI) window.player.updateHealthUI();
                window.gameEnhancements?.visualEffects?.createComboText(window.player.x, window.player.y, `+${amount} HP`, '#00FF00');
            }
        }
        
        giveAmmo(amount) {
            if (window.player?.currentWeapon) {
                window.player.currentWeapon.totalAmmo += amount;
                window.gameEnhancements?.visualEffects?.createComboText(window.player.x, window.player.y, `+${amount} 弹药`, '#00BFFF');
            }
        }
        
        tempSpeedBoost() {
            if (window.player) {
                const originalSpeed = window.player.speed;
                window.player.speed *= 1.5;
                window.gameEnhancements?.visualEffects?.createComboText(window.player.x, window.player.y, '速度爆发!', '#FFFF00');
                
                setTimeout(() => {
                    if (window.player && window.player.speed > originalSpeed) {
                        window.player.speed = originalSpeed;
                    }
                }, 3000);
            }
        }
        
        getComboInfo() {
            return {
                current: this.combo,
                best: this.bestCombo,
                multiplier: this.comboMultiplier.toFixed(1)
            };
        }
    }
    
    // 动态事件系统 - 随机事件和补给空投
    class DynamicEventSystem {
        constructor(gameEngine) {
            this.gameEngine = gameEngine;
            this.events = [];
            this.lastEventTime = 0;
            this.eventInterval = 30000; // 30秒一次事件
            this.activeEvents = [];
        }
        
        initialize() {
            this.setupEventTypes();
            console.log('⚡ 动态事件系统已激活');
        }
        
        setupEventTypes() {
            this.eventTypes = [
                {
                    name: '补给空投',
                    probability: 0.4,
                    execute: () => this.supplyDrop()
                },
                {
                    name: '血月',
                    probability: 0.2,
                    execute: () => this.bloodMoon()
                },
                {
                    name: '幸运时刻',
                    probability: 0.3,
                    execute: () => this.luckyMoment()
                },
                {
                    name: '僵尸潮',
                    probability: 0.1,
                    execute: () => this.zombieWave()
                }
            ];
        }
        
        update(deltaTime) {
            const now = Date.now();
            
            // 检查是否触发新事件
            if (now - this.lastEventTime > this.eventInterval) {
                this.triggerRandomEvent();
                this.lastEventTime = now;
            }
            
            // 更新活跃事件
            this.activeEvents = this.activeEvents.filter(event => {
                event.update(deltaTime);
                return !event.finished;
            });
        }
        
        triggerRandomEvent() {
            if (window.gameEngine?.gameState !== 'playing') return;
            
            const rand = Math.random();
            let cumulative = 0;
            
            for (const eventType of this.eventTypes) {
                cumulative += eventType.probability;
                if (rand <= cumulative) {
                    eventType.execute();
                    console.log(`⚡ 触发事件: ${eventType.name}`);
                    break;
                }
            }
        }
        
        supplyDrop() {
            const dropX = Math.random() * 800 + 100;
            const dropY = Math.random() * 600 + 100;
            
            // 创建空投视觉效果
            window.gameEnhancements?.visualEffects?.createSupplyDropEffect(dropX, dropY);
            
            // 3秒后创建补给品
            setTimeout(() => {
                const supplies = [
                    { type: 'health', amount: 50, color: '#00FF00' },
                    { type: 'ammo', amount: 30, color: '#00BFFF' },
                    { type: 'damage', amount: 1.2, color: '#FF4500' }
                ];
                
                supplies.forEach((supply, index) => {
                    this.gameEngine.powerUps.push({
                        x: dropX + (index - 1) * 30,
                        y: dropY,
                        width: 20,
                        height: 20,
                        type: 'supply_drop',
                        subType: supply.type,
                        amount: supply.amount,
                        color: supply.color,
                        collected: false
                    });
                });
            }, 3000);
            
            this.showEventNotification('📦 补给空投incoming!', '#00FF00');
        }
        
        bloodMoon() {
            this.activeEvents.push({
                name: 'bloodMoon',
                duration: 15000, // 15秒
                startTime: Date.now(),
                finished: false,
                applied: false,
                update: function(deltaTime) {
                    const elapsed = Date.now() - this.startTime;
                    
                    if (!this.applied) {
                        // 增强所有僵尸
                        window.gameEngine?.zombies.forEach(zombie => {
                            zombie.speed *= 1.5;
                            zombie.maxHealth *= 1.2;
                            zombie.health = zombie.maxHealth;
                        });
                        this.applied = true;
                        
                        // 屏幕效果
                        window.gameEnhancements?.visualEffects?.bloodMoonEffect();
                    }
                    
                    if (elapsed >= this.duration) {
                        this.finished = true;
                        // 恢复正常
                        window.gameEngine?.zombies.forEach(zombie => {
                            zombie.speed /= 1.5;
                            zombie.maxHealth /= 1.2;
                        });
                    }
                }
            });
            
            this.showEventNotification('🌙 血月降临! 僵尸增强!', '#FF0000');
        }
        
        luckyMoment() {
            this.activeEvents.push({
                name: 'luckyMoment',
                duration: 10000, // 10秒
                startTime: Date.now(),
                finished: false,
                update: function(deltaTime) {
                    const elapsed = Date.now() - this.startTime;
                    
                    // 击杀僵尸时额外奖励
                    if (window.gameEnhancements?.comboSystem) {
                        window.gameEnhancements.comboSystem.comboMultiplier *= 2;
                    }
                    
                    if (elapsed >= this.duration) {
                        this.finished = true;
                        if (window.gameEnhancements?.comboSystem) {
                            window.gameEnhancements.comboSystem.comboMultiplier /= 2;
                        }
                    }
                }
            });
            
            this.showEventNotification('⭐ 幸运时刻! 双倍奖励!', '#FFD700');
        }
        
        zombieWave() {
            // 生成额外僵尸
            for (let i = 0; i < 5; i++) {
                setTimeout(() => {
                    if (window.levelManager?.zombieSpawner) {
                        const edge = Math.floor(Math.random() * 4);
                        let x, y;
                        
                        switch(edge) {
                            case 0: x = Math.random() * 1000; y = -50; break;
                            case 1: x = 1050; y = Math.random() * 750; break;
                            case 2: x = Math.random() * 1000; y = 800; break;
                            case 3: x = -50; y = Math.random() * 750; break;
                        }
                        
                        const zombie = window.levelManager.zombieSpawner.createZombie('normal', x, y);
                        window.gameEngine?.zombies.push(zombie);
                    }
                }, i * 2000);
            }
            
            this.showEventNotification('🧟 僵尸潮来袭!', '#8B0000');
        }
        
        showEventNotification(message, color) {
            window.gameEnhancements?.visualEffects?.createEventNotification(message, color);
        }
    }
    
    // 视觉效果增强系统
    class VisualEffectsSystem {
        constructor(gameEngine) {
            this.gameEngine = gameEngine;
            this.shakeIntensity = 0;
            this.shakeDuration = 0;
            this.shakeTime = 0;
        }
        
        initialize() {
            console.log('✨ 视觉效果系统已激活');
        }
        
        update(deltaTime) {
            // 更新屏幕震动
            if (this.shakeTime > 0) {
                this.shakeTime -= deltaTime;
                if (this.shakeTime <= 0) {
                    this.shakeIntensity = 0;
                }
            }
        }
        
        screenShake(intensity, duration = 200) {
            // 震动效果已禁用
            return;
        }
        
        getShakeOffset() {
            if (this.shakeTime <= 0) return { x: 0, y: 0 };
            
            const intensity = this.shakeIntensity * (this.shakeTime / this.shakeDuration);
            return {
                x: (Math.random() - 0.5) * intensity,
                y: (Math.random() - 0.5) * intensity
            };
        }
        
        createExplosion(x, y, radius) {
            // this.screenShake(15, 500); // 禁用爆炸震动
            
            // 爆炸粒子
            for (let i = 0; i < 20; i++) {
                const angle = (Math.PI * 2 * i) / 20;
                const speed = Math.random() * 300 + 100;
                
                this.gameEngine.particles.push({
                    x: x,
                    y: y,
                    vx: Math.cos(angle) * speed,
                    vy: Math.sin(angle) * speed,
                    life: Math.random() * 1 + 0.5,
                    maxLife: Math.random() * 1 + 0.5,
                    color: ['#FF4500', '#FF6347', '#FFD700', '#FF0000'][Math.floor(Math.random() * 4)],
                    size: Math.random() * 8 + 4
                });
            }
        }
        
        createImpact(x, y, color) {
            for (let i = 0; i < 8; i++) {
                this.gameEngine.particles.push({
                    x: x,
                    y: y,
                    vx: (Math.random() - 0.5) * 100,
                    vy: (Math.random() - 0.5) * 100,
                    life: 0.5,
                    maxLife: 0.5,
                    color: color,
                    size: Math.random() * 4 + 2
                });
            }
        }
        
        createDodgeTrail(x, y) {
            for (let i = 0; i < 5; i++) {
                this.gameEngine.particles.push({
                    x: x + (Math.random() - 0.5) * 20,
                    y: y + (Math.random() - 0.5) * 20,
                    vx: 0,
                    vy: 0,
                    life: 0.3,
                    maxLife: 0.3,
                    color: '#FFFFFF',
                    size: Math.random() * 3 + 1
                });
            }
        }
        
        createComboText(x, y, text, color) {
            this.gameEngine.floatingTexts.push({
                x: x,
                y: y,
                text: text,
                color: color,
                life: 2,
                maxLife: 2,
                vy: -50,
                size: 16
            });
        }
        
        createDamageText(x, y, damage, color) {
            this.gameEngine.floatingTexts.push({
                x: x,
                y: y,
                text: `-${damage}`,
                color: color,
                life: 1,
                maxLife: 1,
                vy: -30,
                size: 14
            });
        }
        
        createSupplyDropEffect(x, y) {
            // 创建降落伞效果
            for (let i = 0; i < 15; i++) {
                this.gameEngine.particles.push({
                    x: x + (Math.random() - 0.5) * 40,
                    y: y - 100 - Math.random() * 50,
                    vx: (Math.random() - 0.5) * 20,
                    vy: 50 + Math.random() * 30,
                    life: 3,
                    maxLife: 3,
                    color: '#FFFFFF',
                    size: Math.random() * 6 + 3
                });
            }
        }
        
        createEventNotification(message, color) {
            // 在屏幕中央显示事件通知
            this.gameEngine.floatingTexts.push({
                x: 500,
                y: 100,
                text: message,
                color: color,
                life: 3,
                maxLife: 3,
                vy: 0,
                size: 24,
                centered: true
            });
        }
        
        bloodMoonEffect() {
            // 红色屏幕效果
            const canvas = this.gameEngine.canvas;
            const overlay = document.createElement('div');
            overlay.style.cssText = `
                position: fixed;
                top: 0; left: 0;
                width: 100%; height: 100%;
                background: rgba(255, 0, 0, 0.1);
                pointer-events: none;
                z-index: 1000;
                animation: bloodPulse 2s infinite;
            `;
            
            const style = document.createElement('style');
            style.textContent = `
                @keyframes bloodPulse {
                    0%, 100% { opacity: 0.1; }
                    50% { opacity: 0.2; }
                }
            `;
            document.head.appendChild(style);
            document.body.appendChild(overlay);
            
            setTimeout(() => {
                document.body.removeChild(overlay);
                document.head.removeChild(style);
            }, 15000);
        }
    }
    
    // 主增强系统管理器
    class GameEnhancements {
        constructor(gameEngine) {
            this.gameEngine = gameEngine;
            this.environmentSystem = new EnvironmentSystem(gameEngine);
            this.dodgeSystem = new DodgeSystem();
            this.comboSystem = new ComboSystem();
            this.dynamicEventSystem = new DynamicEventSystem(gameEngine);
            this.visualEffects = new VisualEffectsSystem(gameEngine);
            this.initialized = false;
        }
        
        initialize() {
            if (this.initialized) return;
            
            try {
                this.environmentSystem.initialize();
                this.dodgeSystem.initialize();
                this.comboSystem.initialize();
                this.dynamicEventSystem.initialize();
                this.visualEffects.initialize();
                
                this.initialized = true;
                console.log('🎮 游戏增强系统全部激活！');
                
                // 显示欢迎消息
                setTimeout(() => {
                    this.visualEffects.createEventNotification('🎯 游戏增强已激活!', '#00FF00');
                }, 2000);
                
            } catch (error) {
                console.error('游戏增强系统初始化失败:', error);
            }
        }
        
        update(deltaTime) {
            if (!this.initialized) return;
            
            try {
                this.environmentSystem.update(deltaTime);
                this.dodgeSystem.update(deltaTime);
                this.comboSystem.update(deltaTime);
                this.dynamicEventSystem.update(deltaTime);
                this.visualEffects.update(deltaTime);
            } catch (error) {
                console.error('游戏增强系统更新错误:', error);
            }
        }
        
        render(ctx) {
            if (!this.initialized) return;
            
            try {
                // 应用屏幕震动
                const shakeOffset = this.visualEffects.getShakeOffset();
                if (shakeOffset.x !== 0 || shakeOffset.y !== 0) {
                    ctx.save();
                    ctx.translate(shakeOffset.x, shakeOffset.y);
                }
                
                this.environmentSystem.render(ctx);
                
                if (shakeOffset.x !== 0 || shakeOffset.y !== 0) {
                    ctx.restore();
                }
            } catch (error) {
                console.error('游戏增强系统渲染错误:', error);
            }
        }
        
        onLevelStart() {
            if (this.environmentSystem) {
                this.environmentSystem.createEnvironmentObjects();
            }
            if (this.comboSystem) {
                this.comboSystem.resetCombo();
            }
        }
        
        onZombieKilled() {
            if (this.comboSystem) {
                this.comboSystem.addKill();
            }
        }
        
        getStats() {
            return {
                combo: this.comboSystem?.getComboInfo() || {},
                dodgeAvailable: this.dodgeSystem ? !this.dodgeSystem.isDodging : false,
                activeEvents: this.dynamicEventSystem?.activeEvents?.length || 0
            };
        }
    }
    
    // 全局初始化
    window.GameEnhancements = GameEnhancements;
    
    // 自动启动（延迟确保游戏引擎已加载）
    setTimeout(() => {
        if (window.gameEngine && !window.gameEnhancements) {
            window.gameEnhancements = new GameEnhancements(window.gameEngine);
            
            // 等待游戏完全加载
            const initInterval = setInterval(() => {
                if (window.player && window.levelManager) {
                    window.gameEnhancements.initialize();
                    clearInterval(initInterval);
                }
            }, 1000);
        }
    }, 5000);
    
})();